// 用户相关路由配置

const Router = require('@koa/router');
const mongoose = require('mongoose');
const config = require('../../project.config');
const { verify, getToken } = require('../../helpers/token');
const UserModel = mongoose.model('User');

const router = new Router({
  prefix: '/user',
});

// 用户列表接口
router.get('/list', async (ctx) => {
  console.log('--> 调用接口 get /user/list');
  console.log(ctx.query);
  let { page, size, keyword } = ctx.query;
  page = Number(page);
  size = Number(size);
  const list = await UserModel.find({
    username: { $regex: keyword },
  })
    .sort({ _id: -1 })
    .skip((page - 1) * size)
    .limit(size)
    .exec();
  const total = await UserModel.countDocuments().exec();
  ctx.body = {
    msg: '获取用户列表成功',
    code: 1,
    data: {
      list,
      total,
      page,
      size,
    },
  };
});

// 添加用户
router.post('/add', async (ctx) => {
  console.log('--> 调用接口 post /user/add');
  console.log(ctx.request.body);
  const { username, password, character } = ctx.request.body;
  const user = new UserModel({ username, password: password || '123456', character });
  const res = user.save();
  ctx.body = {
    msg: '创建新用户成功',
    code: 1,
    data: res,
  };
});

// 重置密码
router.post('/resetPassword', async (ctx) => {
  console.log('--> 调用接口 post /user/resetPassword');
  console.log(ctx.request.body);
  const { id } = ctx.request.body;
  const findUser = await UserModel.findOne({ _id: id }).exec();
  console.log(findUser);
  findUser.password = config.DEFAULT_PASSWORD;
  const res = await findUser.save();
  ctx.body = {
    msg: '重置密码成功',
    code: 1,
    data: {
      username: res.username,
      _id: res._id,
    },
  };
});

// 删除用户
router.delete('/:id', async (ctx) => {
  const { id } = ctx.params;
  console.log(`--> 调用接口 delete /user/${id}`);
  const delMsg = await UserModel.deleteOne({
    _id: id,
  }).exec();
  ctx.body = {
    msg: '删除用户成功',
    code: 1,
    data: delMsg,
  };
});

// 修改用户角色信息
router.post('/updateCharacter', async (ctx) => {
  console.log('--> 调用接口 post /user/resetPassword');
  console.log(ctx.request.body);
  const { character, userId } = ctx.request.body;
  const user = await UserModel.findOne({ _id: userId }).exec();
  user.character = character;
  const res = await user.save();
  ctx.body = {
    msg: '用户角色修改成功',
    code: 1,
    data: res,
  };
});

// 获取token信息
router.get('/info', async (ctx) => {
  console.log('--> 调用接口 get /user/info');

  // Authorization: Bear $%^789asdsf
  ctx.body = {
    msg: '获取成功',
    code: 1,
    data: await verify(getToken(ctx)),
  };
});

module.exports = router;
